import 'package:flutter/material.dart';
import '../../utils/localization_util.dart';
import '../common/custom_picker.dart';
import '../common/picker_item.dart'; // [MODIFIED] 引入新的 PickerItem

class EditDatePicker extends StatefulWidget {
  final DateTime initialDate;
  final bool showMoment;
  final bool showLaterTime;
  final DateTime? startTime;
  final Locale locale;
  final ValueChanged<DateTime> onDateChanged;

  const EditDatePicker({
    super.key,
    required this.initialDate,
    required this.onDateChanged,
    this.showMoment = true,
    this.showLaterTime = true,
    required this.locale,
    this.startTime,
  });

  @override
  State<EditDatePicker> createState() => _EditDatePickerState();
}

class _EditDatePickerState extends State<EditDatePicker> {
  late DateTime _selectedDate;
  bool _isTimeSelectorVisible = false;
  late final PickerLocalizations l10n;
  final DateTime _now = DateTime.now();

  @override
  void initState() {
    super.initState();
    l10n = PickerLocalizations(widget.locale);
    _selectedDate = _constrainDate(widget.initialDate);
  }

  @override
  void didUpdateWidget(EditDatePicker oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.initialDate != oldWidget.initialDate) {
      setState(() {
        _selectedDate = _constrainDate(widget.initialDate);
      });
    }
  }

  DateTime _constrainDate(DateTime date) {
    DateTime constrained = date;
    if (widget.startTime != null && constrained.isBefore(widget.startTime!)) {
      constrained = widget.startTime!;
    }
    if (!widget.showLaterTime && constrained.isAfter(_now)) {
      constrained = _now;
    }
    final daysInMonth = _getDaysInMonth(constrained.year, constrained.month);
    if (constrained.day > daysInMonth) {
      constrained = DateTime(constrained.year, constrained.month, daysInMonth,
          constrained.hour, constrained.minute);
    }
    return constrained;
  }

  void _handleDateChanged(DateTime newDate) {
    final constrainedDate = _constrainDate(newDate);
    if (constrainedDate != _selectedDate) {
      setState(() {
        _selectedDate = constrainedDate;
      });
    }
    widget.onDateChanged(constrainedDate);
  }

  int _getDaysInMonth(int year, int month) => DateTime(year, month + 1, 0).day;

  bool _isSameDay(DateTime a, DateTime b) =>
      a.year == b.year && a.month == b.month && a.day == b.day;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _buildDivider(),
        AnimatedContainer(
          height: _isTimeSelectorVisible ? 0 : 120,
          duration: const Duration(milliseconds: 200),
          color: Colors.white,
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: _isTimeSelectorVisible
              ? const SizedBox.shrink()
              : Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              _buildYearPicker(),
              _buildMonthPicker(),
              _buildDayPicker(),
            ],
          ),
        ),
        if (widget.showMoment) ...[
          if (_isTimeSelectorVisible)
            _buildTapRow(
             l10n.date,
              "${_selectedDate.year}年${_selectedDate.month}月${_selectedDate.day}日",
            ),
          _buildDivider(),
          if (!_isTimeSelectorVisible)
            _buildTapRow(
              l10n.time,
              "${_selectedDate.hour.toString().padLeft(2, '0')}:${_selectedDate.minute.toString().padLeft(2, '0')}",
            ),
          AnimatedContainer(
            height: !_isTimeSelectorVisible ? 0 : 120,
            duration: const Duration(milliseconds: 200),
            color: Colors.white,
            child: !_isTimeSelectorVisible
                ? const SizedBox.shrink()
                : Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _buildHourPicker(),
                _buildMinutePicker(),
              ],
            ),
          ),
        ]
      ],
    );
  }

  // [REFACTORED] 所有 _build...Picker 方法现在都使用 PickerItem
  Widget _buildYearPicker() {
    return Expanded(
      child: CustomPicker(
        startValue: widget.startTime?.year ?? 1970,
        endValue: _now.year,
        initialValue: _selectedDate.year,
        onValueChanged: (year) => _handleDateChanged(DateTime(year,
            _selectedDate.month, _selectedDate.day, _selectedDate.hour, _selectedDate.minute)),
        itemBuilder: (context, value, isSelected) => PickerItem(
            value: value.toString(), suffix: l10n.year, isSelected: isSelected),
      ),
    );
  }

  Widget _buildMonthPicker() {
    int minMonth = (widget.startTime != null && _selectedDate.year == widget.startTime!.year) ? widget.startTime!.month : 1;
    int maxMonth = (!widget.showLaterTime && _selectedDate.year == _now.year) ? _now.month : 12;
    return Expanded(
      child: CustomPicker(
        startValue: minMonth,
        endValue: maxMonth,
        initialValue: _selectedDate.month,
        onValueChanged: (month) => _handleDateChanged(DateTime(_selectedDate.year,
            month, _selectedDate.day, _selectedDate.hour, _selectedDate.minute)),
        itemBuilder: (context, value, isSelected) => PickerItem(
            value: value.toString().padLeft(2, '0'), suffix: l10n.month, isSelected: isSelected),
      ),
    );
  }

  Widget _buildDayPicker() {
    int minDay = (widget.startTime != null && _selectedDate.year == widget.startTime!.year && _selectedDate.month == widget.startTime!.month) ? widget.startTime!.day : 1;
    int maxDay = (!widget.showLaterTime && _selectedDate.year == _now.year && _selectedDate.month == _now.month) ? _now.day : _getDaysInMonth(_selectedDate.year, _selectedDate.month);
    return Expanded(
      child: CustomPicker(
        startValue: minDay,
        endValue: maxDay,
        initialValue: _selectedDate.day,
        onValueChanged: (day) => _handleDateChanged(DateTime(_selectedDate.year,
            _selectedDate.month, day, _selectedDate.hour, _selectedDate.minute)),
        itemBuilder: (context, value, isSelected) => PickerItem(
            value: value.toString().padLeft(2, '0'), suffix: l10n.day, isSelected: isSelected),
      ),
    );
  }

  Widget _buildHourPicker() {
    int minHour = (widget.startTime != null && _isSameDay(_selectedDate, widget.startTime!)) ? widget.startTime!.hour : 0;
    int maxHour = (!widget.showLaterTime && _isSameDay(_selectedDate, _now)) ? _now.hour : 23;
    return Expanded(
      child: CustomPicker(
        startValue: minHour,
        endValue: maxHour,
        initialValue: _selectedDate.hour,
        onValueChanged: (hour) => _handleDateChanged(DateTime(_selectedDate.year,
            _selectedDate.month, _selectedDate.day, hour, _selectedDate.minute)),
        itemBuilder: (context, value, isSelected) => PickerItem(
            value: value.toString().padLeft(2, '0'), suffix: l10n.hour, isSelected: isSelected),
      ),
    );
  }

  Widget _buildMinutePicker() {
    int minMinute = (widget.startTime != null && _isSameDay(_selectedDate, widget.startTime!) && _selectedDate.hour == widget.startTime!.hour) ? widget.startTime!.minute : 0;
    int maxMinute = (!widget.showLaterTime && _isSameDay(_selectedDate, _now) && _selectedDate.hour == _now.hour) ? _now.minute : 59;
    return Expanded(
      child: CustomPicker(
        startValue: minMinute,
        endValue: maxMinute,
        initialValue: _selectedDate.minute,
        onValueChanged: (minute) {
          final newDate = DateTime(_selectedDate.year, _selectedDate.month,
              _selectedDate.day, _selectedDate.hour, minute);
          setState(() => _selectedDate = newDate);
          widget.onDateChanged(newDate);
        },
        itemBuilder: (context, value, isSelected) => PickerItem(
            value: value.toString().padLeft(2, '0'), suffix: l10n.minute, isSelected: isSelected),
      ),
    );
  }

  // --- Helper Widgets ---
  Widget _buildTapRow(String title, String textValue) {
    return GestureDetector(
      onTap: () => setState(() => _isTimeSelectorVisible = !_isTimeSelectorVisible),
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.symmetric(vertical: 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(title, style: const TextStyle(fontSize: 16, color: Colors.black, fontWeight: FontWeight.w600)),
            Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Text(textValue, style: const TextStyle(fontSize: 16, color: Color.fromRGBO(0, 0, 0, 0.4))),
                const Padding(
                  padding: EdgeInsets.only(top: 2),
                  child: Icon(Icons.keyboard_arrow_right, color: Color.fromRGBO(0, 0, 0, 0.4), size: 16.0),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  Widget _buildDivider() {
    return Container(
      height: 1,
      margin: const EdgeInsets.symmetric(vertical: 4),
      width: double.infinity,
      color: const Color(0xFFF5F5F5),
    );
  }
}
